'use client';
import { createContext, useState, useEffect, ReactNode } from 'react';
import { getSesstion } from '@/lib/session';

interface AuthContextType {
  user: any;
  isAuthenticated: boolean;
  setUser: (user: any) => void;
  logout: () => void;
}

export const AuthContext = createContext<AuthContextType>({
  user: null,
  isAuthenticated: false,
  setUser: () => {},
  logout: () => {}
});

export function AuthProvider({
    children,
}: Readonly<{
    children: ReactNode;
}>) {
    const [user, setUser] = useState(null);
    const [isAuthenticated, setIsAuthenticated] = useState(false);

    useEffect(() => {
        // 检查sessionStorage中的token
        const token = getSesstion('token');
        if (token) {
            // 这里可以添加验证token的逻辑，比如调用/api/auth/me
            setIsAuthenticated(true);
        }
    }, []);

    const logout = () => {
        // 清除sessionStorage
        if (typeof window !== 'undefined') {
            sessionStorage.removeItem('token');
            // 清除cookie
            document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        }
        setUser(null);
        setIsAuthenticated(false);
        window.location.href = '/login';
    };

    const updateAuth = (newUser: any) => {
        setUser(newUser);
        setIsAuthenticated(!!newUser);
    };

    return (
        <AuthContext.Provider value={{ user, isAuthenticated, setUser: updateAuth, logout }}>
            { children }
        </AuthContext.Provider>
    );
}
